var tableIns;
var $;
var form;
var table;
var layer;
var upload;

layui.use(['jquery', 'element', 'table', 'form', 'layer','upload'], function () {
    $ = layui.jquery;
    form = layui.form;
    table = layui.table;
    layer = layui.layer;
    upload = layui.upload; //得到 upload 对象

    var settingss = {
        view: {
            dblClickExpand: false,
            addDiyDom: addDiyDom
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "categroyId",
                pIdKey: "parentId",
                rootPId: -1
            },
            key: {
                enable: true,
                name: "title"
            }
        },
        check: {
            enable: false,
            nocheckInherit: true
        },
        callback: {
            onRightClick: onRightClick,
            beforeRename: beforeRename,
            onClick: chooseNode,
        }
    };
    function addDiyDom(treeId, treeNode) {
        var switchObj = $("#" + treeNode.tId + "_switch"),
            icoObj = $("#" + treeNode.tId + "_ico");
        switchObj.remove();
        icoObj.parent().before(switchObj);
        var spantxt = $("#" + treeNode.tId + "_span").html();
        if (spantxt.length > 6) {
            spantxt = spantxt.substring(0, 6) + "...";
            $("#" + treeNode.tId + "_span").html(spantxt);
        }
    }
    //鼠标右键展示选项
    function onRightClick(event, treeId, treeNode) {
        if (treeNode && !treeNode.noR) {
            zTree.selectNode(treeNode);
            showRMenu("node", event.clientX, event.clientY);
        }
    }

    //修改前判断
    function beforeRename(treeId, treeNode, newName) {
        if (newName.length == 0) {
            layer.msg("节点名称不能为空.");
            var zTree = $.fn.zTree.getZTreeObj("ztree");
            setTimeout(function () {
                zTree.editName(treeNode)
            }, 10);
            return false;
        }
        return true;
    }

    function showRMenu(type, x, y) {
        $("#rMenu ul").show();
        if (type == "root") {
            $("#m_del").hide();
        } else {
            $("#m_del").show();
        }

        y += document.body.scrollTop;
        x += document.body.scrollLeft;
        rMenu.css({"top": y + "px", "left": x + "px", "visibility": "visible"});
        $("body").bind("mousedown", onBodyMouseDown);
    }

    function hideRMenu() {
        if (rMenu) rMenu.css({"visibility": "hidden"});
        $("body").unbind("mousedown", onBodyMouseDown);
    }

    function onBodyMouseDown(event) {
        if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
            rMenu.css({"visibility": "hidden"});
        }
    }

    //添加节点
    addTreeNode = function addTreeNode() {
        hideRMenu();
        var nodes = zTree.getSelectedNodes();
        var parentId = nodes[0].categroyId;
        layer.open({
            type: 1,
            title: "添加节点",
            area: ['400px', '250px'],
            shade: 0.4,
            offset: 'auto',
            content: "<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>" +
                "<label class='layui-input-label'>添加分类：</label>"
                + "<input type='text' name='title' style='width:220px;height:30px;'id='addNode' lay-verify='required' placeholder='商品分类'>"
                + "</div></form>",
            btn: ['添加', '取消'],
            yes: function () {
                var title = $("#addNode").val();
                var jsProductCategroy = {
                    'parentId': parentId,
                    'title': title,
                    'createId': createId,
                    'categroy': 1,
                }
                $.ajax({
                    url: '/JsGoodsTree/addGoodsCategroy',
                    dataType: 'json',
                    data: jsProductCategroy,
                    success: function (data) {
                        if (data.data) {
                            layer.msg("添加成功");
                            location.reload();
                        } else {
                            layer.msg("添加失败");
                        }
                    }
                });
            }
        })
    }

    /*高级检索*/
    retrieval = function retrieval() {
        layer.open({
            type: 2,
            title: "高级检索",
            area: ['650px', '380px'],
            maxmin:true,
            content: "/goods/goods-search-table.html",
            shade: 0,
            offset: 'auto',
            cancel: function(index, layero){
                layer.close(index)
                return false;
            }
        })
    }

    //搜索
    form.on('submit(search)', function (data) {
        console.log(data);
        console.log(data.field);
        $.ajax({
            url: '/goodsTable/getTable',
            type: 'post',
            dataType: 'json',
            data: data.field,
            success: function (data) {
                tablereload(data.data);
            }
        });
    });

    //删除节点
    removeTreeNode = function removeTreeNode() {
        hideRMenu();
        var nodes = zTree.getSelectedNodes();
        var categroyId = nodes[0].categroyId;
        layer.confirm("确认删除" + nodes[0].title + "商品类?",{icon:3,title:'提示'},function (index) {
            if (nodes[0].isParent) {
                layer.msg("不能删除该目录，请从最底层目录开始删除!");
                return false;
            }
            $.ajax({
                url: '/JsGoodsTree/delTreeNode',
                data: {"categroyId": categroyId},
                dataType: 'json',
                success: function (data) {
                    if (data.data) {
                        layer.msg("删除成功");
                        location.reload();
                        return true;
                    } else {
                        layer.msg("删除失败");
                        return false;
                    }
                }
            });
        })
    }
    //修改节点
    edit = function edit() {
        hideRMenu();
        var nodes = zTree.getSelectedNodes();
        var categroyId = nodes[0].categroyId;
        layer.open({
            type: 1,
            title: '修改节点',
            area: ['400px', '250px'],
            shade: 0,
            offset: 'auto',
            content:
                "<form class='layui-form'>" +
                "<div class='layui-form-item' style='margin: 20px;'>"+
                "<label class='layui-input-label'>修改分类：</label>"
                +"<input type='text' name='title' style='width:220px;height:30px;'id='updateNode' lay-verify='required' placeholder='商品分类'>"
                +"</div>" +
                "</form>",
            btn : ['确定', '取消'],
            yes: function () {
                var newName = $("#updateNode").val();
                var jsProductCategroy = {
                    'categroyId': categroyId,
                    'title': newName,
                    'updateId': updateId
                }
                if (newName.length != 0) {
                    $.ajax({
                        url: '/JsGoodsTree/updateGoodsCategroy',
                        data: jsProductCategroy,
                        dataType: 'json',
                        success: function (data) {
                            if (data.data) {
                                layer.msg("修改成功");
                                document.location.reload();
                                return true;
                            } else {
                                layer.msg("修改失败");
                                return false;
                            }
                        }
                    });
                } else {
                    layer.msg("不能为空");
                }
            }
        });
    }

    //点击节点，展示对应类别下商品信息
    function chooseNode(event, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        var nodes = zTree.getSelectedNodes();
        var jsProduct = {
            'categroyId': treeNode.categroyId,
            'result': '1'
        }
        getTable(jsProduct);
    }

    //加载树
    var zTree, rMenu;
    $(document).ready(function () {
        $.ajax({
            url: "/JsGoodsTree/getTree",
            type: 'post',
            dataType: 'json',
            success: function (data) {
                zTree = $.fn.zTree.init($("#ztree"), settingss, data.data); //初始化树
                zTree.expandAll(true);   //true 节点全部展开、false节点收缩
            }
        })
        rMenu = $("#rMenu");
    });

    var jsProduct = {'result': '1'}
    getTable(jsProduct);
    function getTable(jsProduct) {
        jsProduct.updateId = localStorage.getItem("userCode");
        $.ajax({
            url: '/goodsTable/getTable',
            type: 'post',
            dataType: 'json',
            data: jsProduct,
            success: function (data) {
                tablereload(data.data);
            }
        });
    }

    tablereload = function tablereload(data) {
        tableIns = table.render({
            elem: '#table',
            data: data,
            title: '数据列表',
            limit: 6,
            id: 'table',
            toolbar: '#toptool',
            page: {
                layout: ['count', 'prev', 'page', 'next', 'skip', 'refresh'],
                first: "首页",
                last: "尾页",
            },
            size: 'lg',
            cols: [[//定义列
                {type: 'checkbox',width:60},//复选框靠左
                {field: 'productCode', title: '商品编号', align: 'center'},
                {
                    field: "mainImage", title: "商品图片", align: 'center',templet: function (data) {
                        return "<img src=' "+"http://"+ data.mainImage + "' style='width: 100px;height: 100px'/>";
                    }
                },
                {field: 'productName', title: "商品名称", align: 'center'},
                {
                    field: 'currentpriceProduct',
                    title: "商品价格",
                    align: 'center',
                    templet: function (data) {
                        return "￥" + data.currentpriceProduct;
                    }
                },
                {
                    field: 'productSate',
                    title: "上架/下架",
                    align: 'center',
                    templet: function (data) {
                        if (data.productSate == 1) {
                            var radio = '<a href="javascript:updateStatus(' + data.productId + "," + data.productSate + ');"><input class="layui-input swi" type="checkbox" name="sate" lay-skin="switch" lay-text="上架|下架" lay-filter="switchTest" value="' + data.productSate + '" checked></a>'
                        } else {
                            var radio = '<a href="javascript:updateStatus(' + data.productId + ',' + data.productSate + ');"><input class="layui-input swi" type="checkbox" name="sate" lay-skin="switch" lay-text="上架|下架" lay-filter="switchTest" value="' + data.productSate + '"></a>'
                        }
                        return radio;
                    }
                },
                {field: 'title', title: "商品分类", align: 'center'},
                {field: 'productLabel', title: "商品标签", align: 'center'},
                {
                    field: 'result', title: "审核状态", align: 'center', templet: function (data) {
                        if (data.result == 1) {
                            data.result = "审核通过";
                        } else if (data.result == 2) {
                            data.result = "待审核";
                        } else {
                            data.result = "审核未通过";
                        }
                        return "<div style='margin: -8px;height: 28px'>" + data.result + "</div>" +
                            "<a href='javascript:detailed(" + data.productId + ");' style='color: #0EAA9E'>审核详细</a>";
                    }
                },
                {
                    field: '', title: "操作", align: 'center', templet: function (data) {
                        return "<div>" +
                            "<a href='javascript:getProduct(" + data.productId + ");' style='color: #0EAA9E;margin-right: 10px'>查看</a>" +
                            "<a href='javascript:updateProduct(" + data.productId + ");' style='color: #0EAA9E'>编辑</a><br/>" +
                            "<a href='javascript:goGoodsLog("+data.productId+");' style='color: #0EAA9E; margin-right: 10px'>日志</a>" +
                            "<a href='javascript:delProduct(" + data.productId + ");' style='color: #0EAA9E'>删除</a>" +
                            "</div>";
                    }
                },
            ]],
        });
    }

    /*商品修改*/
    updateProduct = function updateProduct(productId) {
        $.ajax({
            url: "/goodsTable/getGoodsMsg",
            type: "post",
            dataType: "json",
            data: {"productId": productId},
            success: function (data) {
                layer.open({
                    type: 2,
                    title: "修改商品",
                    area: ['950px', '530px'],
                    maxmin: true,
                    shade: 0,
                    offset: ['100px', '220px'],
                    content: "/goods/goods-update.html",
                    success: function (layero, index) {
                        var obj = layero.find('iframe').contents();
                        obj.find("input[name=productCode]").val(data.data.productCode);
                        obj.find("input[name=productId]").val(data.data.productId);
                        obj.find("input[name=productName]").val(data.data.productName);
                        obj.find("input[name=currentpriceProduct]").val(data.data.currentpriceProduct);
                        var a;
                        if (data.data.productSate == 1) {
                            a = '上架';
                        } else {
                            a = '上架';
                        }
                        selectLay(obj, data.data.productSate, a, '#productSate');
                        obj.find("#productLabel").html(data.data.productLabel);
                        obj.find("#productDescription").html(data.data.productDescription);
                        obj.find("#mainImage").attr('src',data.data.mainImage);
                    }
                });

            }
        });

        //加入lay-value的下拉框矫正
        function selectLay(obj, layValue, value, select) {
            obj.find(select).children().each(function () {
                if ($(this).val() == layValue) {
                    var status = 'dd[lay-value=' + layValue + ']';
                    obj.find(select).siblings("div.layui-form-select").find('dl').find(status).click();
                    $(this).parent().append('<option value="' + layValue + '" selected>' + value + '</option>');
                }
            })
        }
    }

    /*查看日志详情*/
    goGoodsLog = function goGoodsLog(productId) {
        console.log(productId);
        localStorage.setItem('productRecId', productId);
        layer.open({
            type: 2,
            title: '日志详细',
            area: ['1500px', '600px'],
            content: '/goods/goods-noly-log.html',
            maxmin: true,
        });
    }

    /*查看商品详情*/
    getProduct = function getProduct(productId) {
        $.ajax({
            url: "/goodsTable/getGoodsMsg",
            type: "post",
            dataType: "json",
            data: {"productId":productId},
            success: function (data) {
                devicesMsg(data);
            },
        })
    }
    //详细数据渲染
    function devicesMsg(data) {
        console.log(data);
        console.log(data.data);
        layer.open({
            type: 2,
            title: "查看商品详细",
            area: ['1050px', '480px'],
            maxmin: true,
            shade: 0,
            offset: ['100px', '220px'],
            content: "/goods/goods-see.html",
            success: function (layero, index) {
                var obj = layero.find('iframe').contents();
                obj.find("#productCode").val(data.data.productCode);
                obj.find("#productName").val(data.data.productName);
                obj.find("#currentpriceProduct").val(data.data.currentpriceProduct);
                obj.find("#title").val(data.data.title);
                if (data.data.productSate == 0) {
                    obj.find("#productSate").val("已删除");
                } else if (data.data.productSate == 1) {
                    obj.find("#productSate").val("上架");
                } else if (data.data.productSate == 2) {
                    obj.find("#productSate").val("下架");
                } else {
                    return "暂定";
                }
                obj.find('#saleNum').val(data.data.saleNum);
                if(data.data.saleNum==null){
                    obj.find("#saleNum").val("0");
                }
                obj.find("#hits").val(data.data.hits);
                obj.find("#collectionNum").val(data.data.collectionNum);
                if(data.data.collectionNum==null){
                    obj.find("#collectionNum").val("0");
                }
                obj.find("#productDescription").val(data.data.productDescription);
                obj.find("#productLabel").val(data.data.productLabel);
                obj.find("#mainImage").attr('src',data.data.mainImage);
            }
        });
    }

    //审核详细
    detailed = function detailed(id) {
        localStorage.setItem('productId', id);
        layer.open({
            type: 2,
            title: '审核详细',
            area: ['700px', '400px'],
            content: '/goods/goods-examine-detailed.html',
            maxmin: true,
        });
    }

    /*开关调整上下架*/
    updateStatus = function updateStatus(productId, productSate) {
        if (productSate == 1) {
            productSate = 2;
        } else {
            productSate = 1;
        }
        $.ajax({
            url: '/goodsTable/updateGoodsSate',
            type: 'post',
            dataType: 'json',
            data: {
                'productId': productId,
                'productSate': productSate
            },
            success: function (data) {
                layer.msg("修改成功");
            }
        })
    }

    /*删除商品*/
    delProduct = function delProduct(id) {
        layer.confirm('是否确定删除此条数据', {
                icon: 3, title: '提示'
            },
            function (index) {
                //通过id删除表格数据
                $.ajax({
                    url: '/goodsTable/delGoods',
                    type: 'post',
                    dataType: 'json',
                    data: {'productId': id,'updateId':createId},
                    success: function (data) {
                        if (data) {
                            var jsProduct = {
                                'result': '1'
                            }
                            getTable(jsProduct);
                            layer.msg("删除成功");
                        } else {
                            layer.msg("删除失败");
                        }
                    }
                });

            }
        )
    }

    /*重置*/
    $("#reset").click(function () {
        var jsProduct = {'result': '1'}
        getTable(jsProduct);
    })
});

//刷新
function Refresh() {
    location.reload();
}

//返回
function goBack() {
    //通过页面查找iframe
    parent.$('#Jump').val('首页');
    parent.getQuick();
    return;
}

/*去添加*/
function goBack() {
    //通过页面查找iframe
    parent.$('#Jump').val('添加商品');
    parent.getQuick();
    return;
}

/*导入Excel*/
function couImport(){
    layer.open({
        type:1,
        title:"导入商品",
        area:['250px','200px'],
        shade:0.4,
        offset:'auto',
        content:"<button class='layui-btn' id='btn' style='margin-top: 19%;margin-left: 32%;'>选择文件</button>",
        success:function(layero,index){
            upload.render({
                elem:"#btn",
                url : '/goodsTable/uploadFile',
                done:function (res,index) {
                    if(res.code==0){
                        layer.close(index);
                        alert(res.data.importStatus);
                        location.reload();
                    }else{
                        layer.msg('导入失败，请确认您导入文件格式是否为xls或xlsx文件',{icon:2});
                    }
                },
                drag:true,
                accept:'file',
                multiple:true
            })
        }
    })
}
